package cn.crdeng.Service.impl;

import cn.crdeng.Service.BlogService;
import cn.crdeng.dao.BlogRepository;
import cn.crdeng.exception.NotFoundException;
import cn.crdeng.po.Blog;
import cn.crdeng.po.BlogQuery;
import cn.crdeng.po.Type;
import cn.crdeng.util.MarkdownUtils;
import cn.crdeng.util.MyBeanUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.criteria.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;

/**
 * 博客业务层
 */
@Service
public class BlogServiceImpl implements BlogService {

    @Autowired
    private BlogRepository blogRepository;

    @Override
    public Blog save(Blog blog) {
        if (blog.getId() == null) {
            blog.setCreateTime(new Date());
            blog.setUpdateTime(new Date());
            blog.setViews(0);
        } else {
            blog.setUpdateTime(new Date());
        }

        return blogRepository.save(blog);
    }

    @Override
    public void delete(Long id) {
        blogRepository.deleteById(id);
    }

    @Override
    public Page<Blog> listBlog(Pageable pageable, BlogQuery blogQuery) {
        return blogRepository.findAll(new Specification<Blog>() {
            @Override
            public Predicate toPredicate(Root<Blog> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) {
                List<Predicate> predicates = new ArrayList<>();
                if (blogQuery.getTitle() != null && !"".equals(blogQuery.getTitle())) {
                    predicates.add(criteriaBuilder.like(root.<String>get("title"), "%" + blogQuery.getTitle() + "%"));
                }
                if (blogQuery.getTypeId() != null) {
                    predicates.add(criteriaBuilder.equal(root.<Type>get("type").get("id"), blogQuery.getTypeId()));
                }
                if (blogQuery.isRecommend()) {
                    predicates.add(criteriaBuilder.equal(root.<Boolean>get("recommend"), blogQuery.isRecommend()));
                }

                query.where(predicates.toArray(new Predicate[predicates.size()]));
                return null;
            }
        }, pageable);
    }

    @Override
    public Blog update(Long id, Blog blog) {
        Blog one = blogRepository.getOne(id);
        if (one == null) {
            throw new NotFoundException("不存在改博客");
        }
        BeanUtils.copyProperties(blog, one);
        return blogRepository.save(one);
    }

    @Override
    public Blog getBlogByID(Long id) {

        return blogRepository.getOne(id);
    }

    @Transactional
    @Override
    public Blog updateBlog(Long id, Blog blog) {
        Blog b = blogRepository.getOne(id);
        if (b == null) {
            throw new NotFoundException("该博客不存在");
        }
        BeanUtils.copyProperties(blog, b, MyBeanUtils.getNullPropertyNames(blog));
        b.setUpdateTime(new Date());
        return blogRepository.save(b);
    }

    @Override
    public Page<Blog> listBlog(Pageable pageable) {
        return blogRepository.findAll(pageable);
    }

    @Override
    public List<Blog> listRecommendBlogTop(Integer size) {
        Pageable pageable = PageRequest.of(0, size, Sort.by(Sort.Direction.DESC, "updateTime"));
        return blogRepository.listBlogRecommend(pageable);
    }

    @Override
    public Page<Blog> searchBlog(String query, Pageable pageable) {
        return blogRepository.searchBlog("%" + query + "%", pageable);
    }

    @Override
    public Blog getAndConvert(Long id) {
        Blog one = blogRepository.getOne(id);
        if (one == null) {
            throw new NotFoundException("改博客不存在");
        }
        Blog blog = new Blog();
        BeanUtils.copyProperties(one, blog);
        blog.setContent(MarkdownUtils.markdownToHtmlExtensions(blog.getContent()));
        return blog;
    }

    @Override
    public Page<Blog> listBlogByTagId(Pageable pageable, Long id) {
        return blogRepository.findAll(new Specification<Blog>() {
            @Override
            public Predicate toPredicate(Root<Blog> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) {
                Join join = root.join("tags");
                Predicate predicate = criteriaBuilder.equal(join.get("id"), id);
                return predicate;
            }
        }, pageable);
    }

    @Override
    public LinkedHashMap<String, List<Blog>> archive() {
        //获取Blog的年份
        List<String> years = blogRepository.getYear();
       //创建一个数组储存
        LinkedHashMap linkedHashMap = new LinkedHashMap();

        for (String year : years) {
            List<Blog> blogs = blogRepository.listBlogByYear(year);
            linkedHashMap.put(year, blogs);
        }
        return linkedHashMap;
    }

    /**
     * 添加浏览次数
     * @param id
     * @return
     */
    @Override
    public int addViews(Long id) {
        return blogRepository.addViews(id);
    }


}
